<?php
namespace Admin\Controller;

use Util\AccessController;

require_once(THINK_PATH . "Library/Util/WxRedEnvelope/init.php");
require_once(THINK_PATH . "Library/Util/CompaniesToPay/init.php");

class GetOrderController extends AccessController {

    public function Index() {
        //快递公司
        $LS1 = Service('Book', 'region');
        $YYpdata = $LS1->find(array('region_name' => '快递公司'));
        $YYsondata = $LS1->query(array('region_fid' => $YYpdata['region_id']));
        $this->KDGS = $YYsondata;

        //品相审核回复
        $YYpdata = $LS1->find(array('region_name' => '品相审核回复'));
        $YYsondata = $LS1->query(array('region_fid' => $YYpdata['region_id']));
        $this->PXSH = $YYsondata;

        $this->CSDATAS = json_encode($_GET);
        $this->CSDATA = $_GET;
        $this->ORDER_STATE = json_encode(C('HS_ORDER_STATE'));
        $this->ORDER_STATE_SHOW = C('HS_ORDER_STATE_SHOW');

        $where['order_leixing'] = 3;
        $_GET['order_type'] ? $where['order_type'] = $_GET['order_type'] : 1;
        $_GET['order_id'] ? $where['order_id'] = $_GET['order_id'] : 1;
        $_GET['order_code'] ? $where['order_code'] = $_GET['order_code'] : 1;
        $_GET['order_phone'] ? $where['order_phone'] = $_GET['order_phone'] : 1;
        $_GET['order_address_name'] ? $where['order_address_name'] = $_GET['order_address_name'] : 1;
        $_GET['order_express_return'] ? $where['order_express_return'] = $_GET['order_express_return'] : 1;
        $_GET['user_id'] ? $where['ts_order.user_id'] = $_GET['user_id'] : 1;

        $OnePageShow = 5;
        $LS = Service('Order', 'order');
        $count = $LS->count($where);
        $Page = new \Think\NewPage($count, $OnePageShow);
        $show = $Page->show(); // 分页显示输出
        $limit = $Page->limit();

        $order = 'order_start_time DESC';
        $join = 'left join ts_u_user on ts_u_user.user_id = ts_order.user_id ';
        $join1 = 'left join ts_group_order_log on ts_group_order_log.ORDER_ID = ts_order.order_id ';
        $files = 'ts_order.*,ts_u_user.user_wx_name,ts_group_order_log.GROUP_ID';
        $DATA = $LS->query($where, $limit, $files, $order, $join, $join1);
        //代发货订单自动拆单操作
        if ($_GET['STATE'] == 2 && $_GET['HS'] == 0) {
            foreach ($DATA as $k => $v) {
                $this->BreakUpOrder($v['order_id']);
            }
        }
        $this->show = $show;
        $this->data = $DATA;

        $this->display();
    }


    /*
     * 修改订单价格
     */
    public function updatecost() {
        $where['order_id'] = $_POST['ID'];
        if (is_numeric($_POST['money']) && $_POST['money'] >= 0) {
            $save['order_money'] = $_POST['money'];
            $LS = Service('Order', 'order');
            $finddata = $LS->find($where);
            if ($finddata) {
                $updateOK = $LS->update($where, $save);
                echo $updateOK;
            } else {
                echo 0;
            }
        } else {
            echo -1;
        }
    }

    /*
     * 修改书籍价格
     */
    public function updatebookcost() {
        $where['ob_id'] = $_POST['ID'];
        if (is_numeric($_POST['money']) && $_POST['money'] >= 0) {
            $LS = Service('Order', 'order_book');
            $finddata = $LS->find($where);
            if ($finddata) {
                $save['ob_pay_money'] = $_POST['money'];
                $save['info'] = $finddata['info'] . '--->由账号《' . $this->S('USER_NAME') . '修改价格为：' . $_POST['money'];
                $updateOK = $LS->update($where, $save);
                echo $updateOK;
            } else {
                echo 0;
            }
        } else {
            echo -1;
        }
    }

    /*
     * 呼叫快递上门收货
     */
    public function HjKd() {
        $LS = Service('Order', 'order');
        $Odata = $LS->find(array('order_id' => $_POST['order_id']));
        $UserLS = Service('M', 'u_user');
        $UserData = $UserLS->find(array('user_id' => $Odata['user_id']));

        $OBLS = Service('M', 'order_book');
        $OrderWhere['order_id'] = $_POST['order_id'];
        $OrderWhere['hs_type'] = -1;
        $files = "count(ob_id) as num";
        $num = $OBLS->query($OrderWhere, null, $files);
        //审核不通过书籍通知
        if ($num[0]['num'] > 0) {
            $str = "亲，您的订单中有" . $num[0]['num'] . "本书没有通过审核，
这些本书请不用寄过来；顺丰快递将于您预约的时间免费上门取书，
请准备好要卖的书籍，并保持电话通畅哦！";
            $order_type_str = '已安排快递';
            $Send = A('Admin/WxSendMsg');
            $Send->NotHsOrderBook_Send($UserData['user_wx'], $Odata['order_id'], $str, $order_type_str);
        }

        $Send = A('Admin/WxSendMsg');
        $Send->GetOrder_HJKD_Send($UserData['user_wx'], $Odata['order_get_time'], $Odata['order_address'], $Odata['order_id']);
        $where['order_id'] = $_POST['order_id'];
        $save['order_type'] = 2;
        $OK = $LS->update($where, $save);
        echo $OK;
    }

    //填写订单号
    public function FHhanld() {
        $LS = Service('Order', 'order');
        $save['order_express_return_name'] = $_POST['KDNAME'];
        $save['order_express_return'] = $_POST['KDCODE'];
        $where['order_id'] = $_POST['order_id'];
        $OK = $LS->update($where, $save);
        echo $OK;
    }

    //卖书出库操作
    public function bookck() {
        $LS = Service('Order', 'wz');
        $OK = $LS->bookck($_POST['WZ_ID'], $_POST['OB_ID'], $this->S('USER_NAME'));
        echo $OK;
    }

    /*
   * 回收订单状态修改
   */

    public function HSOrderChange() {
        $LS = Service('Order', 'order');
        $Odata = $LS->find(array('order_id' => $_POST['order_id']));
        $UserLS = Service('M', 'u_user');
        $UserData = $UserLS->find(array('user_id' => $Odata['user_id']));
        switch ($_POST['TYPE']) {
            case 2:
                $Send = A('Admin/WxSendMsg');
                $Send->GetOrder_HJKD_Send($UserData['user_wx'], $Odata['order_get_time'], $Odata['order_address'], $Odata['order_id']);
                $save['order_express_return_name'] = $_POST['KDNAME'];
                $save['order_express_return'] = $_POST['KDCODE'];
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                //修改余额
                $user_id = $Odata['user_id'];
                $money = $Odata['order_money'];
                $order_id = $Odata['order_id'];
                $C_LS = Service('Cost', 'cost');
                $C_LS->UserCostAdd($user_id, $money, $order_id);
                //用户通知
                $Send = A('Admin/WxSendMsg');
                $Send->GetOrder_DK_Send($UserData['user_wx'], $order_id, $money);
                //修改卖了多少钱
                $Uwhere['user_id'] = $user_id;
                $Ufiles = 'user_hs_book_money';
                $Umoney = $money;
                $ULS = Service('M', 'u_user');
                $ULS->SetInc($Uwhere, $Ufiles, $Umoney);
                break;
        }
        $where['order_id'] = $_POST['order_id'];
        $save['order_type'] = $_POST['TYPE'];
        $OK = $LS->update($where, $save);
        echo $OK;
    }

    /*
     * 回收书籍品相审核
     */
    public function HSOrderBookSH() {
        $LS = Service('Order', 'order_book');
        $where['ob_id'] = $_POST['ob_id'];
        //修改
        if ($_POST['update']) {
            $data1 = $LS->find($where);
            $save['info'] = $data1['info'] . '-->由' . $this->S('USER_NAME') . '修改审核为:' . $_POST['info'];
            $save['state'] = $_POST['state'];
        } else {
            $save['state'] = $_POST['state'];
            if ($_POST['state'] == -1) {
                $save['info'] = '由' . $this->S('USER_NAME') . '审核，理由:' . $_POST['info'];
            } else {
                $save['info'] = '由' . $this->S('USER_NAME') . '审核通过。' . $_POST['info'];

            }
        }

        $OK = $LS->update($where, $save);
        $data = $LS->find($where);
        if ($data && $OK) {
            $where1['order_id'] = $data['order_id'];
            $where1['state'] = 0;
            $num = $LS->query($where1);
            if (!$num) {
                $LS1 = Service('Order', 'order');
                $where2['order_id'] = $data['order_id'];
                $save2['order_type'] = 4;
                $sy_cost = $this->js_sy($data['order_id']);
                $save2['order_book_money'] = $sy_cost['book_cost'];
                $save2['order_yh_money'] = $sy_cost['group_cost'];
                $save2['order_money'] = $sy_cost['book_cost'] + $sy_cost['group_cost'];
                $LS1->update($where2, $save2);
                echo (float)$save2['order_money'];
            } else {
                echo 1;
            }
        } else {
            echo -1;
        }

    }

    //计算回收书籍收益 和组团收益
    public function js_sy($order_id) {
        $where1['order_id'] = $order_id;
        $order_book = M('hs_order_sum_pay_view')->where($where1)->find();
        $bl = $this->GroupOrderGetMoney($order_id);
        $res['book_cost'] = $order_book['money'];
        $res['group_cost'] = $bl['bl'] * $order_book['money'];
        return $res;
    }

    //计算订单拼团人数与收益比例
    public function GroupOrderGetMoney($order_id) {
        $logData = M('group_order_log')->where(array('ORDER_ID' => $order_id))->find();
        $numWhere['GROUP_ID'] = $logData['GROUP_ID'];
        $num = M('group_order_log')->where($numWhere)->count();
        $bl = 0;
        switch ($num) {
            case  0:
                $bl = 0;
                break;
            case  1:
                $bl = 0;
                break;
            case  2:
                $bl = 0.3;
                break;
            case  3:
                $bl = 0.5;
                break;
            case  4:
                $bl = 0.7;
                break;
            case  5:
                $bl = 0.9;
                break;
            case  6:
                $bl = 1;
                break;

        }
        $res['num'] = $num;
        $res['bl'] = $bl;
        return $res;
    }

    /*
    * 根据订单书籍出库
    * 拆分订单
    */
    public function BreakUpOrder($order_id) {
        $LS = Service('M', 'order_book');
        $where['ts_order_book.order_id'] = $order_id;
        $join = 'ts_wz on ts_order_book.book_gg_id = ts_wz.GG_ID';
        $DATA = $LS->join($where, $join, null, null, null, 'ob_id');
        $LS1 = Service('Book', 'sg');
        $CKNUM = array();
        foreach ($DATA as $k => $v) {
            $CKDATA = $LS1->GetWZ1($v['WZ_ID']);
            $CKID = $CKDATA['CK_ID'];
            $DATA[$k]['CK'] = $CKID;
            $DATA[$k]['CK_NAME'] = $CKDATA['P'] . $CKDATA['C'] . $CKDATA['Z'];//仓库名称
            if (!in_array($CKID, $CKNUM)) {
                $CKNUM[] = $CKID;
            }
        }


        $LS2 = Service('M', 'order');
        $orderdata = $LS2->find(array('order_id' => $order_id));
        //出库数等于1数不用拆单
        if (count($CKNUM) != 1) {
            $New_order_ALL = array();//所有订单
            $New_order_book_ALL = array();//所有订单书籍
            foreach ($CKNUM as $k => $v) {
                $new_order_id = $orderdata['order_id'] . rand(0, 99) . '_CF_' . $k;
                $new_order_book_num = 0;//新的书籍本数
                $new_order_book_old_money_all = 0;//新的书籍原定价
                $new_order_money_all = 0;//订单总价格
                $CKNAME = '';//仓库名称
                foreach ($DATA as $k1 => $v1) {
                    if ($v1['CK'] == $v) {
                        //生成订单书籍详情数据
                        $new_order_book = $v1;
                        $new_order_book['ob_id'] = 'WXOBID_' . uniqid() . rand(0, 99) . '_CF_' . $k1;
                        $new_order_book['order_id'] = $new_order_id;
                        $new_order_book['info'] = $v1['info'] . '《系统备注：拆单自动生成的订单》';
                        $New_order_book_ALL[] = $new_order_book;//
                        //主表信息
                        $new_order_book_num += $v1['ob_num'];//新的书籍本数
                        $new_order_book_old_money_all += $v1['ob_old_money'];//新的书籍原定价
                        $new_order_money_all += $v1['ob_pay_money'];//订单总价格
                        $CKNAME = $v1['CK_NAME'];
                    }
                }
                //主表信息
                $New_order = $orderdata;
                $New_order['order_id'] = $new_order_id;
                $New_order['order_num'] = $new_order_book_num;
                $New_order['order_old_money'] = $new_order_book_old_money_all;
                $New_order['order_money'] = $new_order_money_all;
                $New_order['order_code'] = 'O_' . uniqid() . rand(0, 99);
                $New_order['order_remarks'] = $New_order['order_remarks'] . "《系统备注：拆单自动生成的订单,由$CKNAME 号仓库发货》";
                if ($v != C('CK_ID')) {//等于主仓库 邮费 优惠信息不变
                    $New_order['order_postage'] = 0;//清除邮费
                    $New_order['coupon_id'] = null;//清除优惠劵id
                }
                $New_order_ALL[] = $New_order;
            }

            //数据修改操作
            $LS3 = Service('Order', 'order');
            $OK = $LS3->BreakUpOrder($order_id, $New_order_ALL, $New_order_book_ALL);
            return $OK;
        }
        return 1;

    }

    /*
     * 回收书籍
     */
    public function  BookIndex() {

        $LS = Service('M', 'order_book');
        $where['state'] = -1;
        $_GET['info'] ? $where['info'] = array('like',
            '%' . $_GET['info'] . '%') : 1;
        $_GET['ob_name'] ? $where['ob_name'] = array('like',
            '%' . $_GET['ob_name'] . '%') : 1;
        $_GET['isbn'] ? $where['isbn'] = $_GET['isbn'] : 1;
        $count = $LS->count($where);
        $Page = new \Think\NewPage($count, 5);
        $show = $Page->show(); // 分页显示输出
        $limit = $Page->limit();
        $this->show = $show;
        $order = I('get.order') != '' && I('get.sort') != '' ? PageSort(I('get.order'), I('get.sort')) : 'isbn desc';
        $DATA = $LS->query($where, $limit, $files = '*', $order);
        $this->DATA = $DATA;
        $this->display();
    }

    //查看团信息
    public function checkGroupOrder() {
        $LS = Service('M', 'hs_group_order_view');
        $where['group_id'] = $_POST['GROUP_ID'];
        $data = $LS->query($where);
        $this->ajaxReturn($data, 'JSON');
    }

    //是否回收书籍
    public function IFHSBOOK() {
        $LS = Service('M', 'order_book');
        $OLS = Service('M', 'order');
        $where['ob_id'] = $_POST['ob_id'];
        $OWhere['order_id'] = $_POST['order_id'];
        if ($_POST['hs_type'] == -1) {
            $save['state'] = -1;
            $save['info'] = '平台不回收';
        }
        $save['hs_type'] = $_POST['hs_type'];
        $OK = $LS->update($where, $save);
        if ($OK) {
            $OrderWhere['order_id'] = $_POST['order_id'];
            $OrderWhere['hs_type'] = 1;
            $files = "SUM(ob_pay_money) as money ,count(*) as num";
            $HS_MONEY = $LS->query($OrderWhere, null, $files);
            $OrderSave['order_money'] = $HS_MONEY[0]['money'] ? $HS_MONEY[0]['money'] : 0;
            $OrderSave['order_num'] = $HS_MONEY[0]['num'];
            if ($HS_MONEY[0]['money'] < 20) {
                echo -2;
            } else {
                //更新订单金额,书籍本书
                $OLS->update($OWhere, $OrderSave);
                echo $HS_MONEY[0]['money'];
            }
        } else {
            echo -1;
        }
    }

    //回收书籍价格低于20 取消订单操作
    public function  DelOrderInHSBook() {
        $OLS = Service('M', 'order');
        $OWhere['order_id'] = $_POST['order_id'];
        $OrderInfo = $OLS->find($OWhere);
        $OrderSave['order_type'] = 6;
        $OrderSave['order_remarks'] = $OrderInfo['order_remarks'] . "\r\n" . '系统回收备注:您的卖书订单有书籍没有通过审核，不满足成单条件，已取消。';
        $OUOK = $OLS->update($OWhere, $OrderSave);
        if ($OUOK) {
            $userInfo = M('u_user')->where(array('user_id' => $OrderInfo['user_id']))->find();
            $str = "您的卖书订单中部分书籍没有通过审核，不满足成单条件，已取消";
            $order_type_str = '已取消';
            $Send = A('Admin/WxSendMsg');
            $DATA = $Send->NotHsOrderBook_Send($userInfo['user_wx'], $_POST['order_id'], $str, $order_type_str);
        }
        echo $OUOK;
    }

    /*
     * 回收书籍入库操作
     */
    public function HsBookRK() {
        if ($_POST['book_id']) {
            $save['BOOK_ID'] = $_POST['book_id'];
            $save['LEVEL'] = '二手书';
            $save['ID'] = $_POST['SG_CODE'];
            $save['USER_ID'] = $_POST['USER_ID'];
            $LS = Service('StoreHouse', 'wz');
            $OK = $LS->addwz($save);
            $OBLS = Service('M', 'order_book');
            $OBwhere['ob_id'] = $_POST['HS_OB_ID'];
            $OBsave['hs_rk_wz'] = $_POST['SG_CODE'];
            $OBLS->update($OBwhere, $OBsave);
            $OK ? $this->success('成功') : $this->error('失败');
        }else{
            $OBLS= Service('M','order_book');
            $OBwhere['order_id'] = $_POST['YJ_order_id'];
            $OBdata = $OBLS->query($OBwhere);
            foreach($OBdata as $k =>$v){
                if($v['book_id']>0 && $v['state'] ==1 && $v['hs_type'] == 1 && $v['hs_rk_wz'] == null ){
                    $save['BOOK_ID'] = $v['book_id'];
                    $save['LEVEL'] = '二手书';
                    $save['ID'] = $_POST['SG_CODE'];
                    $save['USER_ID'] = $_POST['YJ_user_id'];
                    $LS = Service('StoreHouse', 'wz');
                    $OK = $LS->addwz($save);
                    $OBLS = Service('M', 'order_book');
                    $OBwhere['ob_id'] = $v['ob_id'];
                    $OBsave['hs_rk_wz'] = $_POST['SG_CODE'];
                    $OBLS->update($OBwhere, $OBsave);
                }
            }
            $this->success('成功');

        }
    }
    /*
     * 修改回收订单中的书籍
     */
    public function updateOrderBook(){
        //要更改的回收书籍信息
        $OBLS =  Service('M','order_book');
        $OBwhere['ob_id'] = $_POST['old_ob_id'];
        $OBdata = $OBLS->find($OBwhere);

        //改成这本书籍信息
        $BLS = Service('M','book');
        $Bwhere['ID'] = $_POST['book_id'];
        $Bdata = $BLS->find($Bwhere);

        //修改回收书籍状态 不回收
        $OBsave['hs_type'] = -1;
        $OBsave['info'] = '用户扫码不对应书籍，删除';
        $OBOK = $OBLS->update($OBwhere,$OBsave);

        //生成新的回收书籍
        $OBdata['ob_id'] =  $OBdata['ob_id'].'_1';
        $OBdata['book_id'] = $Bdata['ID'];
        $OBdata['ob_name'] =  $Bdata['TITLE'];
        $OBdata['ob_old_money'] = $Bdata['Y_PRICE'];
        $OBdata['ob_pay_money'] =  $Bdata['HS_PRICE'];
        $OBdata['ob_book_pic'] =  $Bdata['PIC_URL'];
        $OBdata['info'] =  '管理员修改生成的回收书籍';
        $OBdata['isbn'] =  $Bdata['ISBN'];
        $OBdata['state'] =  1;
        $OBdata['hs_type'] =  1;
        $OBOK = $OBLS->Add($OBdata);
        $OBOK?$this->success('修改成功'):$this->error('修改失败');
    }

    /*
     * 管理员添加订单备注
     */
    public function AddOrderRemarks(){
        $LS = Service('M','order');
        $where['order_id'] = $_POST['order_id'];
        $save['order_remarks'] = $_POST['order_remarks'];
        $OK = $LS->update($where,$save);
        $OK?$this->success('修改成功'):$this->error('修改失败');
    }

    //微信红包
    public function RedEnvelope() {
        $temp = new \Util\WxRedEnvelope\init();
        /*
        * 设置参数
        * $OPENID 发送红包对象openid
        * $send_name 商户名称
        * $total_amount 付款金额
        * $total_num 红包发放总人数
        * $wishing 红包祝福语
        * $act_name 活动名称
        * $remark 备注
        */
        $temp->set('on7J8046NthBty6rQttBD-uQUSwg', '悦借科技', 100);
        $data = $temp->index();
        dump($json = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA));
    }

    //微信企业到付用户零钱
    public function Pay() {
        $pay = new \Util\CompaniesToPay\init();
        $pay->Setinit('on7J8046NthBty6rQttBD-uQUSwg', $_GET['money']);
        dump($pay->hanld());
        if ($pay->hanld() === true) {
            dump(111);
        }
    }

}